// const util = require('util')
const nodemailer = require('nodemailer')
const mailConfig = require('../config/config').getConf('mail')

const transporter = nodemailer.createTransport({
  host: mailConfig.host,
  port: mailConfig.port,
  secure: mailConfig.secure,
  auth: {
    user: mailConfig.user,
    pass: mailConfig.pass
  }
})

/**
 * @param{Object} mailOptions
 * @param{String} mailOptions.to
 * @param{String} mailOptions.subject
 * @param{String} [mailOptions.text] plain text body choose one between this and html
 * @param{String} [mailOptions.html] html body
 * @return{Promise}
 */
function sendMail (mailOptions) {
  // const send = util.promisify(transporter.sendMail)

  // return send({
  //   from: mailConfig.user,
  //   to: mailOptions.to,
  //   subject: mailOptions.subject,
  //   text: mailOptions.text || '',
  //   html: mailOptions.html || ''
  // })

  return new Promise((resolve, reject) => {
    transporter.sendMail({
      from: mailConfig.user,
      to: mailOptions.to,
      subject: mailOptions.subject,
      text: mailOptions.text || '',
      html: mailOptions.html || ''
    }, (error, info) => {
      if (error) { reject(error) } else { resolve(info) }
    })
  })
}

// transporter.sendMail({
//   from: mailConfig.user,
//   to: '553308706@qq.com',
//   subject: 'test nodemailer',
//   text: 'welcome to use nodemailer'
// }, (err, res) => {
//   if (err) throw err
//   console.log(res)
// })

// sendMail({
//   to: '553308706@qq.com',
//   subject: 'test nodemailer',
//   text: 'welcome to use nodemailer'
// }).then(res => {
//   console.log(res)
// }).catch(err => {
//   console.log(err)
// })

module.exports = {
  sendMail
}

/*
return new Promise((resolve, reject) => {
  transporter.sendMail({
    from: mailConfig.user,
    to: mailOptions.to,
    subject: mailOptions.subject,
    text: mailOptions.text || '',
    html: mailOptions.html || ''
  }, (error, info) => {
    promise = new Promise((resolve, reject) => {
      if (error)
        reject(error)
      else
        resolve(info)
    })
  })
})
*/
